﻿using Kingdee.BOS;
using Kingdee.BOS.App.Data;
using Kingdee.BOS.BusinessEntity.YunZhiJia;
using Kingdee.BOS.Core.DynamicForm;
using Kingdee.BOS.Core.DynamicForm.PlugIn;
using Kingdee.BOS.Core.DynamicForm.PlugIn.Args;
using Kingdee.BOS.Orm.DataEntity;
using Kingdee.BOS.ServiceHelper;
using Kingdee.BOS.Util;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.IO;
using System.Linq;
using System.Net;
using System.Security.Cryptography;
using System.Text;
using System.Text.RegularExpressions;

namespace LiMinCRMPlugin.InterfaceDocking
{
    /// <summary>
    /// 暂估应收审核插件
    /// </summary>
    /// <remarks>
    /// 功能：暂估应收在审核后自动传到CRM。
    /// 创建人：wzx
    /// 创建日期：2024.3.22
    /// 修改信息（1）：修改人，修改日期，修改内容
    /// </remarks>
    [Description("退货暂估应收审核同步至CRM")]
    [HotUpdate]
    public class ProvisionalReceivablesToCRMRuturns : AbstractOperationServicePlugIn
    {
        //OnPreparePropertys 数据加载前，确保需要的属性被加载
        public override void OnPreparePropertys(PreparePropertysEventArgs e)
        {
            base.OnPreparePropertys(e);
            //单据类型
            e.FieldKeys.Add("FBillTypeID");
            //业务类型
            e.FieldKeys.Add("FBUSINESSTYPE");
            //立账类型
            e.FieldKeys.Add("FSetAccountType");           
            //源单内码
            e.FieldKeys.Add("FBILLIDSRC");
            //CRM编码
            e.FieldKeys.Add("F_DEV_CRMNumber");
            //销售订单编码
            e.FieldKeys.Add("F_DEV_OrderNo");           
            //业务日期
            e.FieldKeys.Add("FDate");
            //销售组织
            e.FieldKeys.Add("FSALEORGID");
            //客户
            e.FieldKeys.Add("FCUSTOMERID");
            //销售部门
            e.FieldKeys.Add("FSALEDEPTID");
            //承运商
            e.FieldKeys.Add("F_RDLV_CarrierID");
            //运输单号
            e.FieldKeys.Add("F_RDLV_CarriageNO");
            //交货地点
            e.FieldKeys.Add("F_RDLV_HeadLocationId");

            //备注
            e.FieldKeys.Add("FAR_Remark");
            //发货部门
            e.FieldKeys.Add("F_RDLV_DeliveryDeptID");
            //仓管员
            e.FieldKeys.Add("F_RDLV_StockerID");
            //销售员
            e.FieldKeys.Add("F_DEV_Saler");
            //收款条件
            e.FieldKeys.Add("FPayConditon");
            //核销方式
            e.FieldKeys.Add("FMatchMethodID");
            //是否调货订单
            e.FieldKeys.Add("F_RDLV_Seasoning");
            //是否定制
            e.FieldKeys.Add("F_DEV_Offset");
            //结算方式
            e.FieldKeys.Add("FSettleTypeID");           
            //结算组织
            e.FieldKeys.Add("FSETTLEORGID");
            //币别
            e.FieldKeys.Add("FCURRENCYID");
            //物料编码
            e.FieldKeys.Add("FNumber");
            //批号
            e.FieldKeys.Add("FLot");
            //含税单价
            e.FieldKeys.Add("FTaxPrice");
            //是否赠品
            e.FieldKeys.Add("FIsFree");
            //税率
            e.FieldKeys.Add("FEntryTaxRate");
            //销售数量
            e.FieldKeys.Add("FSalQty");
            //价税合计
            e.FieldKeys.Add("FALLAMOUNTFOR_D");
            //仓库
            e.FieldKeys.Add("F_RDLV_Stock");
            //库存组织
            e.FieldKeys.Add("FSTOCKORGID");
            //结算组织
            e.FieldKeys.Add("FSETTLEORGID");
            //销售单位
            e.FieldKeys.Add("FSalUnitId");
            //计价单位
            e.FieldKeys.Add("FPRICEUNITID");
            //库存单位
            e.FieldKeys.Add("FStockUnitId");
            
            //源单标识
            e.FieldKeys.Add("F_SVZW_Assistant_qtr_dvn");
            //源单编码
            e.FieldKeys.Add("FUseOrgId");
            //同步CRM状态
            e.FieldKeys.Add("F_DEV_FSTATUS");
            //源单类型
            e.FieldKeys.Add("FSOURCETYPE");

            //销售类型
            e.FieldKeys.Add("F_DEV_OrderType");
            //计价数量(暂估数量)
            e.FieldKeys.Add("FPriceQty");
            //销售基本数量
            e.FieldKeys.Add("FSalBaseQty");
            //库存组织
            e.FieldKeys.Add("F_RDLV_NewStockOrgId");


            //核销方式
            e.FieldKeys.Add("F_RDLV_WriteOff");
            //是否淡储
            e.FieldKeys.Add("F_DEV_Survive");
            //进仓编码
            e.FieldKeys.Add("F_RDLV_JCBH");
            //销售主体
            e.FieldKeys.Add("F_RDLV_saleBody");
            //出库单号
            e.FieldKeys.Add("FOUTSTOCKID");


            //汇率
            e.FieldKeys.Add("FExchangeRate");
            //销售订单行号
            e.FieldKeys.Add("FORDERENTRYSEQ");
            //销售订单行内码
            e.FieldKeys.Add("FORDERENTRYID");
            //合同号
            e.FieldKeys.Add("F_QLTK_ContractNumber");

            //交货方式
            e.FieldKeys.Add("F_RDLV_HeadDeliveryWay");
            //形式发票
            e.FieldKeys.Add("F_QLTK_InvoiceNo");
            //行号
            e.FieldKeys.Add("FSeq");
            //海空运费
            e.FieldKeys.Add("F_QLTK_SeaAirFreight");
            //保费
            e.FieldKeys.Add("F_QLTK_PREMIUM");
            //佣金
            e.FieldKeys.Add("F_QLTK_Commission");
            //其他1
            e.FieldKeys.Add("F_QLTK_Other1");
            //是否返利
            e.FieldKeys.Add("F_QLTK_WhetherToRebate");
            //计划跟踪号
            e.FieldKeys.Add("F_QLTK_MtoNo");
            //出库单号(二开)
            e.FieldKeys.Add("F_RDLV_OutBillNo");
            //发货组织
            e.FieldKeys.Add("F_RDLV_NewStockOrgId");


            //CRM出库ID
            e.FieldKeys.Add("F_QLTK_CRMStockID");


            //通知单编码
            e.FieldKeys.Add("F_QLTK_NoticeNo");
            //折扣率
            e.FieldKeys.Add("FEntryDiscountRate");
            //折扣额
            e.FieldKeys.Add("FDISCOUNTAMOUNTFOR");
            //内部结算含税单价
            e.FieldKeys.Add("F_QLTK_SettTaxPrice");
        }
        /// <summary>
        /// 事务结束后事件
        /// </summary>
        /// <param name="e"></param>
        public override void EndOperationTransaction(EndOperationTransactionArgs e)
        {
            base.EndOperationTransaction(e);
            string InvokeType = "";
            if (this.FormOperation.Operation.ToUpper() == "AUDIT")
            {
                InvokeType = "退货暂估应收审核自动上传CRM";
            }
            else if (this.FormOperation.Operation.ToUpper() == "REUPLOADPROVISIONALRECEIVABLES")
            {
                InvokeType = "退货暂估应收手工上传CRM";
            }
            //读取全部的单据,for循环,转换成DynamicObject类型
            foreach (DynamicObject entity in e.DataEntitys)
            {
                string FSetAccountType= entity["FSetAccountType"].ToString();//立账类型
                string SOURCETYPE="";//源单类型 
                string FID = entity["ID"].ToString();
                string FBillNo = entity["BillNo"].ToString();
                string ReturnsFID = "";//销售退货FID
                string ReturnReason=null;
                DynamicObject StockOrg = null;//库存组织
                string StockOrgNo = "";//库存组织编码
                DynamicObject StockDept = null;//库存部门
                string StockDeptNo = "";//库存部门编码
                int StockDeptID = 0;//库存部门内码
                decimal FMustqty = 0;//应退数量
                decimal FRealQty = 0;//实退数量
                string FStocklocId = "";//仓位
                DynamicObject ReturnType = null;//退货类型
                string ReturnTypeNo = "";//退货类型编码
                DynamicObject Stockstatus = null;//库存状态
                string StockstatusNo = "";//库存状态编码
                string FNote = "";//备注
                if (FSetAccountType == "2")//暂估应收且源单是销售退货单
                {
                    DynamicObject SettleOrg = entity["SETTLEORGID"] as DynamicObject;//结算组织
                    string SettleOrgId = "";//结算组织内码
                    string SettleOrgNo = "";//结算组织编码
                    string SettleOrgName = "";
                    if (SettleOrg != null)
                    {
                        SettleOrgId = Convert.ToString(SettleOrg["ID"]);//结算组织内码
                        SettleOrgNo = Convert.ToString(SettleOrg["Number"]);//结算组织编码
                        SettleOrgName = Convert.ToString(SettleOrg["Name"]);//结算组织名称
                    }
                    DynamicObject PayOrg = entity["FPAYORGID"] as DynamicObject;//收款组织
                    string PayOrgId = "";//收款组织内码
                    string PayOrgNo = "";//收款组织编码
                    string PayOrgName = "";
                    if (PayOrg != null)
                    {
                        PayOrgId = Convert.ToString(PayOrg["ID"]);//收款组织内码
                        PayOrgNo = Convert.ToString(PayOrg["Number"]);//收款组织编码
                        PayOrgName = Convert.ToString(PayOrg["Name"]);//收款组织名称
                    }
                    DynamicObject SaleOrg = entity["SALEORGID"] as DynamicObject;//销售组织
                    string SaleOrgId = "";//销售组织内码
                    string SaleOrgNo = "";//销售组织编码
                    string SaleOrgName = "";
                    if (SaleOrg != null)
                    {
                        SaleOrgId = Convert.ToString(SaleOrg["ID"]);//销售组织内码
                        SaleOrgNo = Convert.ToString(SaleOrg["Number"]);//销售组织编码
                        SaleOrgName = Convert.ToString(SaleOrg["Name"]);//销售组织名称
                    }

                    DynamicObject BillType = entity["BillTypeID"] as DynamicObject;//单据类型
                    string BillTypeId = "";//单据类型内码
                    string BillTypeNo = "";//单据类型编码
                    string BillTypeName = "";
                    if (BillType != null)
                    {
                        BillTypeId = Convert.ToString(BillType["ID"]);//单据类型内码
                        BillTypeNo = Convert.ToString(BillType["Number"]);//单据类型编码
                        BillTypeName = Convert.ToString(BillType["Name"]);//单据类型名称
                    }
                    string BUSINESSTYPE = Convert.ToString(entity["FBUSINESSTYPE"]);//业务类型
                    string OrderNo = Convert.ToString(entity["F_DEV_OrderNo"]);//销售订单编码

                    string FSTATUS = Convert.ToString(entity["F_DEV_FSTATUS"]);//同步CRM状态 空-未同步，成功-同步成功，失败-同步失败
                    DynamicObject SaleDept = entity["SALEDEPTID"] as DynamicObject;//销售部门
                    int SaleDeptId=0;
                    string SaleDeptNo = "";
                    if (SaleDept!=null)
                    {
                        SaleDeptId =Convert.ToInt32( SaleDept["ID"].ToString());
                        SaleDeptNo = SaleDept["Number"].ToString();
                    }
                    DynamicObject Saler = entity["F_DEV_Saler"] as DynamicObject;//销售员
                    int SalerId =0;
                    string SalerNo = "";
                    if (Saler != null)
                    {
                        SalerId = Convert.ToInt32(Saler["ID"].ToString());
                        SalerNo = Saler["FStaffNumber"].ToString();
                    }
                    #region 
                    int CONTACTOBJECTID = 0;//联系对象内码
                    string SQLCONTACTOBJECT = string.Format(@"/*dialect*/select FID from V_BD_CONTACTOBJECT
where FNUMBER='{0}' ", SalerNo);
                    DataTable dtCONTACTOBJECT = DBUtils.ExecuteDataSet(this.Context, SQLCONTACTOBJECT).Tables[0];
                    if (dtCONTACTOBJECT.Rows.Count > 0)
                    {
                        CONTACTOBJECTID =Convert.ToInt32(dtCONTACTOBJECT.Rows[0]["FID"]);
                    }
                    string UserAccount = "";//用户账号
                    string SQLUser= string.Format(@"/*dialect*/select FUSERACCOUNT from T_SEC_user where FLINKOBJECT='{0}' ", CONTACTOBJECTID);
                    DataTable dtUser = DBUtils.ExecuteDataSet(this.Context, SQLUser).Tables[0];
                    if (dtUser.Rows.Count > 0)
                    {
                        UserAccount = dtUser.Rows[0]["FUSERACCOUNT"].ToString();
                    }
                    #endregion

                    string FDATE = entity["DATE"].ToString();//业务日期

                    DynamicObject HeadLocation = entity["F_RDLV_HeadLocationId"] as DynamicObject;//交货地点
                    string HeadLocationId = "";
                    string HeadLocationNo = "";
                    if (HeadLocation != null)
                    {
                        HeadLocationId = HeadLocation["ID"].ToString();
                        HeadLocationId = HeadLocation["Number"].ToString();
                    }


                    int Seasoning = 0;
                    if (!entity["F_RDLV_Seasoning"].IsNullOrEmptyOrWhiteSpace())
                    {
                        Seasoning = Convert.ToInt32(entity["F_RDLV_Seasoning"]);//是否调货订单
                    }


                    string FAR_Remark = entity["Remark"].ToString().Replace("%", "%25").Replace("≥", "%E2%89%A5"); ;//备注

                    DynamicObject CURRENCY = entity["CURRENCYID"] as DynamicObject;//币别
                    string CurrencyId = "";
                    string CurrencyNo = "";
                    string CurrencyName = "";
                    if (CURRENCY != null)
                    {
                        CurrencyId = CURRENCY["ID"].ToString();
                        CurrencyNo = CURRENCY["Number"].ToString();
                        CurrencyName=Convert.ToString(CURRENCY["Name"]);
                    }
                    int Offset = 0;
                    if (!entity["F_DEV_Offset"].IsNullOrEmptyOrWhiteSpace())
                    {
                        Offset = Convert.ToInt32(entity["F_DEV_Offset"].ToString());//是否定制
                    }
                    int CustomerId = 0;//客户内码
                    string CustomerNo = "";//客户编码
                    string CustomerName = "";//客户名称
                    DynamicObject Customer = entity["CUSTOMERID"] as DynamicObject;//客户
                    if (Customer != null)
                    {
                        CustomerId = Convert.ToInt32(Customer["Id"]);
                        CustomerNo = Convert.ToString(Customer["Number"]); //客户编码
                        CustomerName = Convert.ToString(Customer["Name"]);//客户名称
                    }
                    string sqlCust = string.Format(@"/*dialect*/select F_RDLV_CRMId from T_BD_CUSTOMER where FCUSTID = '{0}'", CustomerId);
                    DataTable dtCust = DBUtils.ExecuteDataSet(this.Context, sqlCust).Tables[0];
                    int CRMCustID = 0;
                    if (dtCust != null && dtCust.Rows.Count > 0 && dtCust.Rows[0]["F_RDLV_CRMId"].ToString() != "" && dtCust.Rows[0]["F_RDLV_CRMId"].ToString() != " " && dtCust.Rows[0]["F_RDLV_CRMId"].ToString() != null)
                    {
                        CRMCustID = Convert.ToInt32(dtCust.Rows[0]["F_RDLV_CRMId"]);
                    }

                    string HEADDELIVERYWAYNo = "";//交货方式编码
                    DynamicObject HEADDELIVERYWAY = entity["F_RDLV_HEADDELIVERYWAY"] as DynamicObject;//交货方式
                    int DELIVERYWAY = 0;//CRM交货方式枚举
                    if (HEADDELIVERYWAY != null)
                    {
                        HEADDELIVERYWAYNo = HEADDELIVERYWAY["FNUMBER"].ToString();
                    }
                    if (HEADDELIVERYWAYNo == "JHFS02_SYS")
                    {
                        DELIVERYWAY = 1;
                    }

                    int PayConditonId = 0;//收款条件内码
                    string PayConditonNo = "";//收款条件编码
                    string PayConditonName = "";//收款条件名称
                    DynamicObject PayConditon = entity["PayConditon"] as DynamicObject;//收款条件
                    if (PayConditon != null)
                    {
                        PayConditonId = Convert.ToInt32(PayConditon["Id"]);
                        PayConditonNo = Convert.ToString(PayConditon["Number"]); //收款条件编码
                        PayConditonName = Convert.ToString(PayConditon["Name"]);//收款条件名称
                    }

                    int StockerId = 0;//仓管员内码
                    string StockerNo = "";//仓管员编码
                    string StockerName = "";//仓管员编码
                    DynamicObject Stocker = entity["F_RDLV_StockerID"] as DynamicObject;//仓管员
                    if (Stocker != null)
                    {
                        StockerId = Convert.ToInt32(Stocker["Id"]);
                        StockerNo = Convert.ToString(Stocker["FStaffNumber"]); //仓管员编码
                        StockerName = Convert.ToString(Stocker["Name"]);//仓管员名称
                    }

                    int CarrierId = 0;//承运商内码
                    string CarrierNo = "";//承运商编码
                    string CarrierName = "";//承运商名称
                    DynamicObject Carrier = entity["F_RDLV_CarrierID"] as DynamicObject;//承运商
                    if (Carrier != null)
                    {
                        CarrierId = Convert.ToInt32(Carrier["Id"]);
                        CarrierNo = Convert.ToString(Carrier["Number"]); //承运商编码
                        CarrierName = Convert.ToString(Carrier["Name"]);//承运商名称
                    }
                    string CarriageNO = "";//运输单号
                    CarriageNO = entity["F_RDLV_CarriageNO"].ToString().Trim();//运输单号

                    int DeliveryDeptId = 0;//发货部门内码
                    string DeliveryDeptNo = "";//发货部门编码
                    string DeliveryDeptName = "";//发货部门名称
                    DynamicObject DeliveryDept = entity["F_RDLV_DeliveryDeptID"] as DynamicObject;//发货部门
                    if (DeliveryDept != null)
                    {
                        DeliveryDeptId = Convert.ToInt32(DeliveryDept["Id"]);
                        DeliveryDeptNo = Convert.ToString(DeliveryDept["Number"]); //发货部门编码
                        DeliveryDeptName = Convert.ToString(DeliveryDept["Name"]);//发货部门名称
                    }

                    int FMatchMethodID = 0;
                    if (!entity["F_RDLV_WriteOff"].IsNullOrEmptyOrWhiteSpace())
                    {
                        FMatchMethodID = Convert.ToInt32(entity["F_RDLV_WriteOff"]);//核销方式
                    }

                    var PAYABLEFIN = entity["AP_PAYABLEFIN"] as DynamicObjectCollection;
                    int SettleTypeId = 0;//结算方式内码
                    string SettleTypeNo = "";//结算方式编码
                    string SettleTypeName = "";//结算方式名称
                    decimal ExchangeRate = 0;//汇率
                    if (PAYABLEFIN!=null)
                    {
                        
                        DynamicObject SettleType = PAYABLEFIN[0]["FSettleTypeID"] as DynamicObject;//结算方式
                        if (SettleType != null)
                        {
                            SettleTypeId = Convert.ToInt32(SettleType["Id"]);
                            SettleTypeNo = Convert.ToString(SettleType["Number"]); //结算方式编码
                            SettleTypeName = Convert.ToString(SettleType["Name"]);//结算方式名称
                        }

                        ExchangeRate = Convert.ToDecimal(PAYABLEFIN[0]["FExchangeRate"]);//汇率
                    }

                    string OrderTypeNo = "";//销售类型编码
                    string OrderTypeName = "";//销售类型名称
                    DynamicObject OrderType = entity["F_DEV_OrderType"] as DynamicObject;//销售类型
                    if (OrderType != null)
                    {
                        OrderTypeNo = Convert.ToString(OrderType["Number"]); //销售类型编码
                        OrderTypeName = Convert.ToString(OrderType["Name"]);//销售类型名称
                    }
                    string CRMNumber = Convert.ToString(entity["F_DEV_CRMNumber"]);//CRM编码
                    int Survive = 0;//是否淡储
                    if (!entity["F_DEV_Survive"].IsNullOrEmpty()&& entity["F_DEV_Survive"].ToString()!=" ")
                    {
                        Survive = Convert.ToInt32(entity["F_DEV_Survive"]);//是否淡储
                    }
                    string JCBM = "";//进仓编码
                    JCBM = Convert.ToString(entity["F_RDLV_JCBH"]).Trim();//进仓编码
                    string SaleBodyNo = "";//销售类型编码
                    string SaleBodyName = "";//销售类型名称
                    DynamicObject SaleBody = entity["F_RDLV_saleBody"] as DynamicObject;//销售主体
                    if (SaleBody != null)
                    {
                        SaleBodyNo = Convert.ToString(SaleBody["Number"]); //销售主体编码
                        SaleBodyName = Convert.ToString(SaleBody["Name"]);//销售主体名称
                    }

                    string InvoiceNo = "";//形式发票
                    string ContractNumber = "";//合同号
                    InvoiceNo = Convert.ToString(entity["F_QLTK_InvoiceNo"]).Trim();//形式发票
                    ContractNumber = Convert.ToString(entity["F_QLTK_ContractNumber"]).Trim();//合同号

                    DynamicObjectCollection FEntityDetail = entity["AP_PAYABLEENTRY"] as DynamicObjectCollection;//明细 

                    List<ProvisionalReceivablesReturnsModel.detailList> detailList = new List<ProvisionalReceivablesReturnsModel.detailList>();//明细数据组
                    foreach (var item in FEntityDetail)
                    {
                        string FENTRTYID = Convert.ToString(item["id"]);
                        SOURCETYPE = Convert.ToString(item["FSOURCETYPE"]);                        
                        string sqlLK = string.Format(@"/*dialect*/select FSBILLID, FSID from t_AR_receivableEntry_LK where FRULEID = 'AR_ReturnToReceivableMap' and FENTRYID = {0}", FENTRTYID);
                        DataTable  dtLK = DBUtils.ExecuteDataSet(this.Context, sqlLK).Tables[0];
                        string ReturnsFENTRTYID = "";//销售退货单FENTRTYID
                        if (dtLK.Rows.Count>0)
                        {
                            ReturnsFENTRTYID = Convert.ToString(dtLK.Rows[0]["FSID"]);
                            ReturnsFID = Convert.ToString(dtLK.Rows[0]["FSBILLID"]);
                        }

                        string sqlReturns = string.Format(@"/*dialect*/select F_RDLV_ReturnReason,FReturnReason, FStockOrgId,FStockDeptId,FMustqty,FRealQty,FStocklocId,FReturnType,FStockstatusId,b.FNote from T_SAL_RETURNSTOCK a
inner join T_SAL_RETURNSTOCKENTRY b on a.FID=b.FID
where FENTRYID='{0}'", ReturnsFENTRTYID);
                        DataTable dtReturns = DBUtils.ExecuteDataSet(this.Context, sqlReturns).Tables[0];
                        #region 销售退货信息
                        if (dtReturns.Rows.Count > 0)
                        {
                            ReturnReason= Convert.ToString(dtReturns.Rows[0]["F_RDLV_ReturnReason"]);
                            StockDeptID = Convert.ToInt32(dtReturns.Rows[0]["FStockDeptId"]);                         
                            FMustqty = Convert.ToDecimal(dtReturns.Rows[0]["FMustqty"]);
                            FRealQty = Convert.ToDecimal(dtReturns.Rows[0]["FRealQty"]);
                            FStocklocId= Convert.ToString(dtReturns.Rows[0]["FStocklocId"]);
                            ReturnType= dtReturns.Rows[0]["FReturnType"] as DynamicObject;
                            if (ReturnType != null)
                            {
                                ReturnTypeNo = Convert.ToString(ReturnType["Number"]);
                            }
                            Stockstatus = dtReturns.Rows[0]["FStockstatusId"] as DynamicObject;
                            if (Stockstatus != null)
                            {
                                StockstatusNo = Convert.ToString(Stockstatus["Number"]);
                            }
                            FNote = Convert.ToString(dtReturns.Rows[0]["FNote"]);
                        }
                        #endregion
                        string MaterialId = "";//物料内码
                        string MaterialNo = "";//物料编码
                        string MaterialName = "";//物料名称
                        string Specification = "";//规格型号
                        DynamicObject Material = item["MATERIALID"] as DynamicObject;//物料
                        if (Material != null)
                        {
                            MaterialId = Convert.ToString(Material["Id"]);
                            MaterialNo = Convert.ToString(Material["Number"]); //物料编码
                            MaterialName = Convert.ToString(Material["Name"]); //物料名称
                            Specification = Convert.ToString(Material["Specification"]);
                        }
                        decimal TaxPrice = Convert.ToDecimal(item["TaxPrice"]);//含税单价
                        string IsFree = Convert.ToString(item["IsFree"]);//是否赠品
                        int ZP = 0;
                        if (IsFree=="true")
                        {
                            ZP = 1;
                        }
                        decimal EntryTaxRate = Convert.ToDecimal(item["EntryTaxRate"]);//税率
                        decimal SalQty = Convert.ToDecimal(item["SalQty"]);//销售数量
                        decimal FALLAMOUNTFOR_D = Convert.ToDecimal(item["FALLAMOUNTFOR_D"]);//价税合计

                        string FLotNO = "";
                        DynamicObject FLot = item["FLot"] as DynamicObject;//批号
                        if (FLot != null)
                        {
                            FLotNO = Convert.ToString(FLot["Number"]);//批号
                        }

                        string SalUnitId = "";//销售单位内码
                        string SalUnitNo = "";//销售单位编码
                        DynamicObject SalUnit = item["SalUnitId"] as DynamicObject;//销售单位
                        if (SalUnit != null)
                        {
                            SalUnitId = Convert.ToString(SalUnit["Id"]);
                            SalUnitNo = Convert.ToString(SalUnit["Number"]); //销售单位编码
                        }

                        string PriceUnitId = "";//计价单位内码
                        string PriceUnitNo = "";//计价单位编码
                        DynamicObject PriceUnit = item["PRICEUNITID"] as DynamicObject;//计价单位单位
                        if (PriceUnit != null)
                        {
                            PriceUnitId = Convert.ToString(PriceUnit["Id"]);
                            PriceUnitNo = Convert.ToString(PriceUnit["Number"]); //计价单位编码
                        }

                        string StockUnitId = "";//库存单位内码
                        string StockUnitNo = "";//库存单位编码
                        DynamicObject StockUnit = item["StockUnitId"] as DynamicObject;//库存单位单位
                        if (StockUnit != null)
                        {
                            StockUnitId = Convert.ToString(StockUnit["Id"]);
                            StockUnitNo = Convert.ToString(StockUnit["Number"]); //库存单位编码
                        }

                       
                         StockOrg = item["F_RDLV_NewStockOrgId"] as DynamicObject;//库存组织
                        if (StockOrg != null)
                        {
                            StockOrgNo = Convert.ToString(StockOrg["Number"]); //库存组织编码
                        }

                        

                        string StockId = "";//仓库内码
                        string StockNo = "";//仓库编码
                        DynamicObject Stock = item["F_RDLV_Stock"] as DynamicObject;//仓库
                        if (Stock != null)
                        {
                            StockId = Convert.ToString(Stock["Id"]);
                            StockNo = Convert.ToString(Stock["Number"]); //仓库编码
                        }

                        string NewStockOrgId = "";//发货组织内码
                        string NewStockOrgNo = "";//发货组织编码
                        DynamicObject NewStockOrg = item["F_RDLV_NewStockOrgId"] as DynamicObject;//发货组织
                        if (NewStockOrg != null)
                        {
                            NewStockOrgId = Convert.ToString(NewStockOrg["Id"]);
                            NewStockOrgNo = Convert.ToString(NewStockOrg["Number"]); //发货组织编码
                        }

                        //                        string sqlSOCCOST = string.Format(@"/*dialect*/select FBaseQty from T_AR_SOCCOSTENTRY a
                        //inner join t_AR_receivableEntry b on a.FENTRYID=b.FENTRYID
                        //where b.FENTRYID={0}", FENTRTYID);
                        //                        DataTable dtSOCCOST = DBUtils.ExecuteDataSet(this.Context, sqlSOCCOST).Tables[0];
                        //                        decimal BaseQty = Convert.ToDecimal(dtSOCCOST.Rows[0]["FBaseQty"]);
                        decimal BaseQty = 0;
                        BaseQty=Convert.ToDecimal(item["SalBaseQty"]);
                        decimal PriceQty = Convert.ToDecimal(item["PriceQty"]);

                        string SOURCEBILLTYPEID = "";
                        DynamicObject SOURCEBILLTYPE = item["SOURCEBILLTYPEID"] as DynamicObject;//源单单据类型
                        if (SOURCEBILLTYPE != null)
                        {
                            SOURCEBILLTYPEID = Convert.ToString(SOURCEBILLTYPE["ID"]); //源单单据类型内码
                        }

                        string OUTSTOCKNo = "";
                        DynamicObject OUTSTOCK = item["OUTSTOCKID"] as DynamicObject;//出库单号
                        if (OUTSTOCK != null)
                        {
                            OUTSTOCKNo = Convert.ToString(OUTSTOCK["ID"]); //出库单号编码
                        }
                        string OutBillNo = Convert.ToString(item["F_RDLV_OutBillNo"]);//退货单号

                        string ORDERENTRYSEQ = Convert.ToString(item["ORDERENTRYSEQ"]);//销售订单行号
                        string ORDERENTRYID = Convert.ToString(item["ORDERENTRYID"]);//销售订单明细内码

                        decimal SeaAirFreight = Convert.ToDecimal(item["F_QLTK_SeaAirFreight"]);//海空运费
                        decimal PREMIUM = Convert.ToDecimal(item["F_QLTK_PREMIUM"]);//保费
                        decimal Commission = Convert.ToDecimal(item["F_QLTK_Commission"]);//佣金
                        decimal Other1 = Convert.ToDecimal(item["F_QLTK_Other1"]);//其他1
                        int WhetherToRebate = 0;
                        //if (item["F_QLTK_WhetherToRebate"]!=null&&Convert.ToString(item["F_QLTK_WhetherToRebate"])!="" && Convert.ToString(item["F_QLTK_WhetherToRebate"]) != " ")
                        if (!item["F_QLTK_WhetherToRebate"].IsNullOrEmptyOrWhiteSpace())
                        {
                            WhetherToRebate = Convert.ToInt32(item["F_QLTK_WhetherToRebate"]);//是否返利

                        }
                        string Seq = Convert.ToString(item["Seq"]);//行号
                        string MtoNo = "";//计划跟踪号
                        MtoNo = Convert.ToString(item["F_QLTK_MtoNo"]).Trim();//计划跟踪号
                        string CRMStockID = Convert.ToString(item["F_QLTK_CRMStockID"]);//CRM出库单明细
                        string NoticeNumber = Convert.ToString(item["F_QLTK_NoticeNo"]);//通知单编码

                        decimal EntryDiscountRate = Convert.ToDecimal(item["EntryDiscountRate"]);//折扣率
                        decimal DISCOUNTAMOUNTFOR = Convert.ToDecimal(item["FDISCOUNTAMOUNTFOR"]);//折扣额
                        decimal SettTaxPrice = 0;
                        SettTaxPrice = Convert.ToDecimal(item["F_QLTK_SettTaxPrice"]);//内部结算含税单价
                        #region 应收单detail数组
                        ProvisionalReceivablesReturnsModel.operate operate = new ProvisionalReceivablesReturnsModel.operate();
                        operate.action = "SaveOrUpdate";

                        ProvisionalReceivablesReturnsModel.dataList dataList = new ProvisionalReceivablesReturnsModel.dataList();
                        dataList.ck = StockId;
                        dataList.ddmxxh = FENTRTYID;
                        dataList.cpbm = MaterialNo;
                        dataList.cpmc = MaterialName;
                        dataList.sfzp = ZP;
                        dataList.xssl = FMustqty;
                        dataList.stsl = FRealQty;
                        dataList.thrq = FDATE;
                        dataList.ggxh = Specification;
                        dataList.kcdw = StockUnitNo;
                        dataList.cw = FStocklocId;
                        if (ReturnTypeNo== "THLX01_SYS")
                        {
                            dataList.thlx = 0;
                        }
                        else if (ReturnTypeNo == "THLX02_SYS")
                        {
                            dataList.thlx = 1;
                        }
                        else if (ReturnTypeNo == "THLX03_SYS")
                        {
                            dataList.thlx = 2;
                        }

                        if (StockstatusNo == "KCZT01_SYS")
                        {
                            dataList.kczt = 0;
                        }
                        else if (StockstatusNo == "KCZT02_SYS")
                        {
                            dataList.kczt = 1;
                        }
                        else if (StockstatusNo == "KCZT03_SYS")
                        {
                            dataList.kczt = 2;
                        }
                        else if (StockstatusNo == "KCZT04_SYS")
                        {
                            dataList.kczt = 3;
                        }
                        else if (StockstatusNo == "KCZT07_SYS")
                        {
                            dataList.kczt = 4;
                        }
                        else if (StockstatusNo == "KCZT08_SYS")
                        {
                            dataList.kczt = 5;
                        }
                        else if (StockstatusNo == "KCZT99_SYS")
                        {
                            dataList.kczt = 6;
                        }
                        dataList.bz = FNote;
                        dataList.zgsl = PriceQty;
                        dataList.jbdwsl = BaseQty;
                        dataList.yddjlx = SOURCEBILLTYPEID;
                        dataList.tkdh = OutBillNo;
                        dataList.hsdj = TaxPrice;
                        dataList.erpckdnm = ReturnsFID;
                        dataList.ckdmxnm = ReturnsFENTRTYID;
                        dataList.zgysydbm =FBillNo;
                        dataList.sl = EntryTaxRate;
                        dataList.jjsl = PriceQty;

                        dataList.hkyf = SeaAirFreight;
                        dataList.yj = Commission;
                        dataList.bf = PREMIUM;
                        dataList.qt1 = Other1;
                        dataList.sfcyfl = WhetherToRebate;
                        dataList.sczlh = MtoNo;
                        dataList.ddxh = ORDERENTRYSEQ;
                        dataList.ddmxnm = ORDERENTRYID;
                        dataList.xsddh = OrderNo;
                        dataList.jjdw = PriceUnitNo;
                        dataList.kczz = StockOrgNo;
                        dataList.jszz = SettleOrgNo;
                        dataList.pch = FLotNO;
                        dataList.jshj = FALLAMOUNTFOR_D;
                        dataList.ckdmx = CRMStockID;
                        dataList.zk = EntryDiscountRate;
                        dataList.zke = DISCOUNTAMOUNTFOR;
                        dataList.nbjshsdj = SettTaxPrice;
                        ProvisionalReceivablesReturnsModel.detailList detailList1 = new ProvisionalReceivablesReturnsModel.detailList();
                        detailList1.operate = operate;
                        detailList1.data = dataList;
                        detailList.Add(detailList1);

                        #endregion
                    }
                    #region 应收单mainTable数组
                    ProvisionalReceivablesReturnsModel.mainTableList mainTable = new ProvisionalReceivablesReturnsModel.mainTableList();
                    mainTable.thyy = ReturnReason;
                    mainTable.djnm = FID;
                    mainTable.djbh = FBillNo;
                    mainTable.crmbm = CRMNumber;
                    mainTable.ddbh = OrderNo;
                    mainTable.kcbm = StockDeptNo;
                    mainTable.xsy = SalerNo;
                    mainTable.xszz = SaleOrgNo;
                    mainTable.rq = FDATE;                
                    mainTable.sfdhdd = Seasoning;
                    mainTable.jsbb = CurrencyName;
                    mainTable.sfdz = Offset;
                    mainTable.thkh = CRMCustID;
                    mainTable.kczz = StockOrgNo;
                    mainTable.cgy = StockerNo;
                    mainTable.jhdd = HeadLocationNo;
                    mainTable.xslx = OrderTypeNo;
                    mainTable.sfdc = Survive;
                    mainTable.jcbm = JCBM;
                    mainTable.hxfs = FMatchMethodID;
                    mainTable.xszt = SaleBodyNo;
                    mainTable.hth = ContractNumber;
                    mainTable.jsfs = SettleTypeNo;
                    mainTable.sktj = PayConditonNo;
                    mainTable.hl = ExchangeRate;

                    mainTable.fph = InvoiceNo;
                    mainTable.jhfs = DELIVERYWAY;
                    mainTable.ysdh = CarriageNO;
                    mainTable.cys = CarrierNo;
                    #endregion


                    if (this.FormOperation.Operation.ToUpper() == "AUDIT"&& SOURCETYPE == "SAL_RETURNSTOCK")
                    {
                        string resultSearch = CRMSearchRETURNSTOCK(FID, SalerNo);
                        //不存在数据，需要新增
                        if (resultSearch == "无结果")
                        {
                            Return resultAdd = CRMAddRETURNSTOCK(mainTable, detailList, SalerNo);
                            if (resultAdd.status == "1")
                            {
                                #region 退货单写日志(插入一张CRM接口日志单据，更新单据上的接口调用方式/调用时间/调用结果）
                                Common.InterfaceLog interfaceLog = new Common.InterfaceLog();
                                interfaceLog.FBILLNO = FBillNo;
                                interfaceLog.FBILLID = FID;
                                interfaceLog.FDATE = System.DateTime.Now;
                                interfaceLog.FINTERNAME = "新增退货单";
                                interfaceLog.FInvokeType = "";
                                interfaceLog.Ftoken = "";
                                interfaceLog.FSTATUS = "成功";
                                interfaceLog.FRequsetData = "{\"data\":[{\"operationinfo\":{\"operator\":\""+SalerNo+"\",\"operationDate\":\"" + DateTime.Now.ToString("yyyy-MM-dd") + "\",\"operationTime\":\"" + DateTime.Now.ToString("HH:mm:ss") + "\"},\"mainTable\":" + JsonConvert.SerializeObject(mainTable) + ",\"detail1\":" + JsonConvert.SerializeObject(detailList) + "}],\"header\":{\"systemid\":\"kingde\",\"" + DateTime.Now + "\":\"currentTimeTamp \",\"Md5\":\"\"}}";
                                interfaceLog.FReturnData = JsonConvert.SerializeObject(resultAdd.datajson);
                                interfaceLog.FRequest = "{\"data\":[{\"operationinfo\":{\"operator\":\""+SalerNo+"\",\"operationDate\":\"" + DateTime.Now.ToString("yyyy-MM-dd") + "\",\"operationTime\":\"" + DateTime.Now.ToString("HH:mm:ss") + "\"},\"mainTable\":" + JsonConvert.SerializeObject(mainTable) + ",\"detail1\":" + JsonConvert.SerializeObject(detailList) + "}],\"header\":{\"systemid\":\"kingde\",\"" + DateTime.Now + "\":\"currentTimeTamp \",\"Md5\":\"\"}}";
                                interfaceLog.FReturn = JsonConvert.SerializeObject(resultAdd.datajson);
                                string LogSql = interfaceLog.WriteCRMLogSql();//获取写入日志单据的SQL
                                List<string> sqlList = new List<string>();
                                if (!string.IsNullOrEmpty(LogSql))
                                {
                                    sqlList.Add(LogSql);
                                }
                                //更新单据
                                string updateSql = string.Format(@"/*dialect*/ update t_AR_receivable set F_DEV_FDATE='{0}',F_DEV_FSTATUS='{1}' 
                    where FID={2}", interfaceLog.FDATE, interfaceLog.FSTATUS, FID);
                                sqlList.Add(updateSql);
                                DBServiceHelper.ExecuteBatch(this.Context, sqlList);
                                #endregion
                            }                          
                            else
                            {
                                #region 退货单写日志(插入一张CRM接口日志单据，更新单据上的接口调用方式/调用时间/调用结果）
                                Common.InterfaceLog interfaceLog = new Common.InterfaceLog();
                                interfaceLog.FBILLNO = FBillNo;
                                interfaceLog.FBILLID = FID;
                                interfaceLog.FDATE = System.DateTime.Now;
                                interfaceLog.FINTERNAME = "新增退货单";
                                interfaceLog.FInvokeType = "";
                                interfaceLog.Ftoken = "";
                                interfaceLog.FSTATUS = "失败";
                                interfaceLog.FRequsetData = "{\"data\":[{\"operationinfo\":{\"operator\":\""+SalerNo+"\",\"operationDate\":\"" + DateTime.Now.ToString("yyyy-MM-dd") + "\",\"operationTime\":\"" + DateTime.Now.ToString("HH:mm:ss") + "\"},\"mainTable\":" + JsonConvert.SerializeObject(mainTable) + ",\"detail1\":" + JsonConvert.SerializeObject(detailList) + "}],\"header\":{\"systemid\":\"kingde\",\"" + DateTime.Now + "\":\"currentTimeTamp \",\"Md5\":\"\"}}";
                                interfaceLog.FReturnData = JsonConvert.SerializeObject(resultAdd.datajson);
                                interfaceLog.FRequest = "{\"data\":[{\"operationinfo\":{\"operator\":\""+SalerNo+"\",\"operationDate\":\"" + DateTime.Now.ToString("yyyy-MM-dd") + "\",\"operationTime\":\"" + DateTime.Now.ToString("HH:mm:ss") + "\"},\"mainTable\":" + JsonConvert.SerializeObject(mainTable) + ",\"detail1\":" + JsonConvert.SerializeObject(detailList) + "}],\"header\":{\"systemid\":\"kingde\",\"" + DateTime.Now + "\":\"currentTimeTamp \",\"Md5\":\"\"}}";
                                interfaceLog.FReturn = JsonConvert.SerializeObject(resultAdd.datajson);
                                string LogSql = interfaceLog.WriteCRMLogSql();//获取写入日志单据的SQL
                                List<string> sqlList = new List<string>();
                                if (!string.IsNullOrEmpty(LogSql))
                                {
                                    sqlList.Add(LogSql);
                                }
                                //更新单据
                                string updateSql = string.Format(@"/*dialect*/ update t_AR_receivable set F_DEV_FDATE='{0}',F_DEV_FSTATUS='{1}' 
                    where FID={2}", interfaceLog.FDATE, interfaceLog.FSTATUS, FID);
                                sqlList.Add(updateSql);
                                DBServiceHelper.ExecuteBatch(this.Context, sqlList);
                                #endregion
                                throw new KDBusinessException("", resultAdd.datajson);
                            }
                        }
                        //存在数据，需要更新
                        else if(resultSearch==FID)
                        {
                            Return resultAUpdate = CRMUpdateRETURNSTOCK(mainTable, detailList, SalerNo);
                            if (resultAUpdate.status == "1")
                            {
                                #region 退货单写日志(插入一张CRM接口日志单据，更新单据上的接口调用方式/调用时间/调用结果）
                                Common.InterfaceLog interfaceLog = new Common.InterfaceLog();
                                interfaceLog.FBILLNO = FBillNo;
                                interfaceLog.FBILLID = FID;
                                interfaceLog.FDATE = System.DateTime.Now;
                                interfaceLog.FINTERNAME = "更新退货单";
                                interfaceLog.FInvokeType = "";
                                interfaceLog.Ftoken = "";
                                interfaceLog.FSTATUS = "成功";
                                interfaceLog.FRequsetData = "{\"data\":[{\"operationinfo\":{\"operator\":\""+SalerNo+"\",\"operationDate\":\"" + DateTime.Now.ToString("yyyy-MM-dd") + "\",\"operationTime\":\"" + DateTime.Now.ToString("HH:mm:ss") + "\"},\"mainTable\":" + JsonConvert.SerializeObject(mainTable) + ",\"detail1\":" + JsonConvert.SerializeObject(detailList) + "}],\"header\":{\"systemid\":\"kingde\",\"" + DateTime.Now + "\":\"currentTimeTamp \",\"Md5\":\"\"}}";
                                interfaceLog.FReturnData = JsonConvert.SerializeObject(resultAUpdate.datajson);
                                interfaceLog.FRequest = "{\"data\":[{\"operationinfo\":{\"operator\":\""+SalerNo+"\",\"operationDate\":\"" + DateTime.Now.ToString("yyyy-MM-dd") + "\",\"operationTime\":\"" + DateTime.Now.ToString("HH:mm:ss") + "\"},\"mainTable\":" + JsonConvert.SerializeObject(mainTable) + ",\"detail1\":" + JsonConvert.SerializeObject(detailList) + "}],\"header\":{\"systemid\":\"kingde\",\"" + DateTime.Now + "\":\"currentTimeTamp \",\"Md5\":\"\"}}";
                                interfaceLog.FReturn = JsonConvert.SerializeObject(resultAUpdate.datajson);
                                string LogSql = interfaceLog.WriteCRMLogSql();//获取写入日志单据的SQL
                                List<string> sqlList = new List<string>();
                                if (!string.IsNullOrEmpty(LogSql))
                                {
                                    sqlList.Add(LogSql);
                                }
                                //更新单据
                                string updateSql = string.Format(@"/*dialect*/ update t_AR_receivable set F_DEV_FDATE='{0}',F_DEV_FSTATUS='{1}' 
                    where FID={2}", interfaceLog.FDATE, interfaceLog.FSTATUS, FID);
                                sqlList.Add(updateSql);
                                DBServiceHelper.ExecuteBatch(this.Context, sqlList);
                                #endregion
                            }
                            else
                            {
                                #region 退货单写日志(插入一张CRM接口日志单据，更新单据上的接口调用方式/调用时间/调用结果）
                                Common.InterfaceLog interfaceLog = new Common.InterfaceLog();
                                interfaceLog.FBILLNO = FBillNo;
                                interfaceLog.FBILLID = FID;
                                interfaceLog.FDATE = System.DateTime.Now;
                                interfaceLog.FINTERNAME = "更新退货单";
                                interfaceLog.FInvokeType = "";
                                interfaceLog.Ftoken = "";
                                interfaceLog.FSTATUS = "失败";
                                interfaceLog.FRequsetData = "{\"data\":[{\"operationinfo\":{\"operator\":\""+SalerNo+"\",\"operationDate\":\"" + DateTime.Now.ToString("yyyy-MM-dd") + "\",\"operationTime\":\"" + DateTime.Now.ToString("HH:mm:ss") + "\"},\"mainTable\":" + JsonConvert.SerializeObject(mainTable) + ",\"detail1\":" + JsonConvert.SerializeObject(detailList) + "}],\"header\":{\"systemid\":\"kingde\",\"" + DateTime.Now + "\":\"currentTimeTamp \",\"Md5\":\"\"}}";
                                interfaceLog.FReturnData = JsonConvert.SerializeObject(resultAUpdate.datajson);
                                interfaceLog.FRequest = "{\"data\":[{\"operationinfo\":{\"operator\":\""+SalerNo+"\",\"operationDate\":\"" + DateTime.Now.ToString("yyyy-MM-dd") + "\",\"operationTime\":\"" + DateTime.Now.ToString("HH:mm:ss") + "\"},\"mainTable\":" + JsonConvert.SerializeObject(mainTable) + ",\"detail1\":" + JsonConvert.SerializeObject(detailList) + "}],\"header\":{\"systemid\":\"kingde\",\"" + DateTime.Now + "\":\"currentTimeTamp \",\"Md5\":\"\"}}";
                                interfaceLog.FReturn = JsonConvert.SerializeObject(resultAUpdate.datajson);
                                string LogSql = interfaceLog.WriteCRMLogSql();//获取写入日志单据的SQL
                                List<string> sqlList = new List<string>();
                                if (!string.IsNullOrEmpty(LogSql))
                                {
                                    sqlList.Add(LogSql);
                                }
                                //更新单据
                                string updateSql = string.Format(@"/*dialect*/ update t_AR_receivable set F_DEV_FDATE='{0}',F_DEV_FSTATUS='{1}' 
                    where FID={2}", interfaceLog.FDATE, interfaceLog.FSTATUS, FID);
                                sqlList.Add(updateSql);
                                DBServiceHelper.ExecuteBatch(this.Context, sqlList);
                                #endregion
                                throw new KDBusinessException("", resultAUpdate.datajson);
                            }
                        }
                        else
                        {
                            #region 退货单写日志(插入一张CRM接口日志单据，更新单据上的接口调用方式/调用时间/调用结果）
                            Common.InterfaceLog interfaceLog = new Common.InterfaceLog();
                            interfaceLog.FBILLNO = FBillNo;
                            interfaceLog.FBILLID = FID;
                            interfaceLog.FDATE = System.DateTime.Now;
                            interfaceLog.FINTERNAME = "更新退货单";
                            interfaceLog.FInvokeType = "";
                            interfaceLog.Ftoken = "";
                            interfaceLog.FSTATUS = "失败";
                            interfaceLog.FRequsetData = "{\"data\":[{\"operationinfo\":{\"operator\":\""+SalerNo+"\",\"operationDate\":\"" + DateTime.Now.ToString("yyyy-MM-dd") + "\",\"operationTime\":\"" + DateTime.Now.ToString("HH:mm:ss") + "\"},\"mainTable\":" + JsonConvert.SerializeObject(mainTable) + ",\"detail1\":" + JsonConvert.SerializeObject(detailList) + "}],\"header\":{\"systemid\":\"kingde\",\"" + DateTime.Now + "\":\"currentTimeTamp \",\"Md5\":\"\"}}";
                            interfaceLog.FReturnData = resultSearch;
                            interfaceLog.FRequest = "{\"data\":[{\"operationinfo\":{\"operator\":\""+SalerNo+"\",\"operationDate\":\"" + DateTime.Now.ToString("yyyy-MM-dd") + "\",\"operationTime\":\"" + DateTime.Now.ToString("HH:mm:ss") + "\"},\"mainTable\":" + JsonConvert.SerializeObject(mainTable) + ",\"detail1\":" + JsonConvert.SerializeObject(detailList) + "}],\"header\":{\"systemid\":\"kingde\",\"" + DateTime.Now + "\":\"currentTimeTamp \",\"Md5\":\"\"}}";
                            interfaceLog.FReturn = resultSearch;
                            string LogSql = interfaceLog.WriteCRMLogSql();//获取写入日志单据的SQL
                            List<string> sqlList = new List<string>();
                            if (!string.IsNullOrEmpty(LogSql))
                            {
                                sqlList.Add(LogSql);
                            }
                            //更新单据
                            string updateSql = string.Format(@"/*dialect*/ update t_AR_receivable set F_DEV_FDATE='{0}',F_DEV_FSTATUS='{1}' 
                    where FID={2}", interfaceLog.FDATE, interfaceLog.FSTATUS, FID);
                            sqlList.Add(updateSql);
                            DBServiceHelper.ExecuteBatch(this.Context, sqlList);
                            #endregion
                            throw new KDBusinessException("", resultSearch);
                        }

                    }
                    else if (this.FormOperation.Operation.ToUpper() == "DELETE" && SOURCETYPE == "SAL_RETURNSTOCK")
                    {
                        if (FSTATUS == "成功")
                        {
                            string resultSearch = CRMSearchRETURNSTOCK(FID, SalerNo);
                            //存在数据，需要新增
                            if (resultSearch == FID)
                            {
                    //            string sql =string.Format(@"select sfscysd from [CRM].[ecology].[dbo].uf_jch_xstkd where djnm='{0}'", FID);
                    //            DataTable dt = DBUtils.ExecuteDataSet(Context, sql).Tables[0];
                    //            if (dt != null && dt.Rows.Count > 0)
                    //            {
                    //                if (Convert.ToString(dt.Rows[0]["sfscysd"]) == "1")
                    //                {
                    //                    throw new KDException("删除失败", "CRM出库已生成应收账单，请先去CRM系统删除下游应收帐单！");
                    //                }
                    //            }
                    //            else
                    //            {
                    //                string resultDelete = CRMDeleteRETURNSTOCK(FID, SalerNo);
                    //                if (resultDelete == "删除成功")
                    //                {
                    //                    #region 退货单写日志(插入一张CRM接口日志单据，更新单据上的接口调用方式/调用时间/调用结果）
                    //                    Common.InterfaceLog interfaceLog = new Common.InterfaceLog();
                    //                    interfaceLog.FBILLNO = FBillNo;
                    //                    interfaceLog.FBILLID = FID;
                    //                    interfaceLog.FDATE = System.DateTime.Now;
                    //                    interfaceLog.FINTERNAME = "删除退货单";
                    //                    interfaceLog.FInvokeType = "";
                    //                    interfaceLog.Ftoken = "";
                    //                    interfaceLog.FSTATUS = "成功";
                    //                    interfaceLog.FRequsetData = "{\"operationinfo\":{\"operator\":\"" + SalerNo + "\"},\"mainTable\":{\"djbm\":\"" + FBillNo + "\"},\"header\":{\"systemid\":\"kingdee\",\"currentDateTime\":\"" + DateTime.Now + "\",\"Md5\":\"md5OfStr \"}}";
                    //                    interfaceLog.FReturnData = resultDelete;
                    //                    interfaceLog.FRequest = "{\"operationinfo\":{\"operator\":\"" + SalerNo + "\"},\"mainTable\":{\"djbm\":\"" + FBillNo + "\"},\"header\":{\"systemid\":\"kingdee\",\"currentDateTime\":\"" + DateTime.Now + "\",\"Md5\":\"md5OfStr \"}}";
                    //                    interfaceLog.FReturn = resultDelete;
                    //                    string LogSql = interfaceLog.WriteCRMLogSql();//获取写入日志单据的SQL
                    //                    List<string> sqlList = new List<string>();
                    //                    if (!string.IsNullOrEmpty(LogSql))
                    //                    {
                    //                        sqlList.Add(LogSql);
                    //                    }
                    //                    DBServiceHelper.ExecuteBatch(this.Context, sqlList);
                    //                    #endregion
                    //                }
                    //                else
                    //                {
                    //                    #region 退货单写日志(插入一张CRM接口日志单据，更新单据上的接口调用方式/调用时间/调用结果）
                    //                    Common.InterfaceLog interfaceLog = new Common.InterfaceLog();
                    //                    interfaceLog.FBILLNO = FBillNo;
                    //                    interfaceLog.FBILLID = FID;
                    //                    interfaceLog.FDATE = System.DateTime.Now;
                    //                    interfaceLog.FINTERNAME = "删除退货单";
                    //                    interfaceLog.FInvokeType = "";
                    //                    interfaceLog.Ftoken = "";
                    //                    interfaceLog.FSTATUS = "失败";
                    //                    interfaceLog.FRequsetData = "{\"operationinfo\":{\"operator\":\"" + SalerNo + "\"},\"mainTable\":{\"djbm\":\"" + FBillNo + "\"},\"header\":{\"systemid\":\"kingdee\",\"currentDateTime\":\"" + DateTime.Now + "\",\"Md5\":\"md5OfStr \"}}";
                    //                    interfaceLog.FReturnData = resultDelete;
                    //                    interfaceLog.FRequest = "{\"operationinfo\":{\"operator\":\"" + SalerNo + "\"},\"mainTable\":{\"djbm\":\"" + FBillNo + "\"},\"header\":{\"systemid\":\"kingdee\",\"currentDateTime\":\"" + DateTime.Now + "\",\"Md5\":\"md5OfStr \"}}";
                    //                    interfaceLog.FReturn = resultDelete;
                    //                    string LogSql = interfaceLog.WriteCRMLogSql();//获取写入日志单据的SQL
                    //                    List<string> sqlList = new List<string>();
                    //                    if (!string.IsNullOrEmpty(LogSql))
                    //                    {
                    //                        sqlList.Add(LogSql);
                    //                    }
                    //                    //更新单据
                    //                    string updateSql = string.Format(@"/*dialect*/ update t_AR_receivable set F_DEV_FDATE='{0}',F_DEV_FSTATUS='{1}' 
                    //where FID={2}", interfaceLog.FDATE, "删除失败", FID);
                    //                    sqlList.Add(updateSql);
                    //                    DBServiceHelper.ExecuteBatch(this.Context, sqlList);
                    //                    #endregion
                    //                    throw new KDBusinessException("", "单据同步删除CRM失败，禁止删除");
                    //                }
                    //            }
                                    string resultDelete = CRMDeleteRETURNSTOCK(FID, SalerNo);
                                    if (resultDelete == "删除成功")
                                    {
                                        #region 退货单写日志(插入一张CRM接口日志单据，更新单据上的接口调用方式/调用时间/调用结果）
                                        Common.InterfaceLog interfaceLog = new Common.InterfaceLog();
                                        interfaceLog.FBILLNO = FBillNo;
                                        interfaceLog.FBILLID = FID;
                                        interfaceLog.FDATE = System.DateTime.Now;
                                        interfaceLog.FINTERNAME = "删除退货单";
                                        interfaceLog.FInvokeType = "";
                                        interfaceLog.Ftoken = "";
                                        interfaceLog.FSTATUS = "成功";
                                        interfaceLog.FRequsetData = "{\"operationinfo\":{\"operator\":\"" + SalerNo + "\"},\"mainTable\":{\"djbm\":\"" + FBillNo + "\"},\"header\":{\"systemid\":\"kingdee\",\"currentDateTime\":\"" + DateTime.Now + "\",\"Md5\":\"md5OfStr \"}}";
                                        interfaceLog.FReturnData = resultDelete;
                                        interfaceLog.FRequest = "{\"operationinfo\":{\"operator\":\"" + SalerNo + "\"},\"mainTable\":{\"djbm\":\"" + FBillNo + "\"},\"header\":{\"systemid\":\"kingdee\",\"currentDateTime\":\"" + DateTime.Now + "\",\"Md5\":\"md5OfStr \"}}";
                                        interfaceLog.FReturn = resultDelete;
                                        string LogSql = interfaceLog.WriteCRMLogSql();//获取写入日志单据的SQL
                                        List<string> sqlList = new List<string>();
                                        if (!string.IsNullOrEmpty(LogSql))
                                        {
                                            sqlList.Add(LogSql);
                                        }
                                        DBServiceHelper.ExecuteBatch(this.Context, sqlList);
                                        #endregion
                                    }
                                    else
                                    {
                                        #region 退货单写日志(插入一张CRM接口日志单据，更新单据上的接口调用方式/调用时间/调用结果）
                                        Common.InterfaceLog interfaceLog = new Common.InterfaceLog();
                                        interfaceLog.FBILLNO = FBillNo;
                                        interfaceLog.FBILLID = FID;
                                        interfaceLog.FDATE = System.DateTime.Now;
                                        interfaceLog.FINTERNAME = "删除退货单";
                                        interfaceLog.FInvokeType = "";
                                        interfaceLog.Ftoken = "";
                                        interfaceLog.FSTATUS = "失败";
                                        interfaceLog.FRequsetData = "{\"operationinfo\":{\"operator\":\"" + SalerNo + "\"},\"mainTable\":{\"djbm\":\"" + FBillNo + "\"},\"header\":{\"systemid\":\"kingdee\",\"currentDateTime\":\"" + DateTime.Now + "\",\"Md5\":\"md5OfStr \"}}";
                                        interfaceLog.FReturnData = resultDelete;
                                        interfaceLog.FRequest = "{\"operationinfo\":{\"operator\":\"" + SalerNo + "\"},\"mainTable\":{\"djbm\":\"" + FBillNo + "\"},\"header\":{\"systemid\":\"kingdee\",\"currentDateTime\":\"" + DateTime.Now + "\",\"Md5\":\"md5OfStr \"}}";
                                        interfaceLog.FReturn = resultDelete;
                                        string LogSql = interfaceLog.WriteCRMLogSql();//获取写入日志单据的SQL
                                        List<string> sqlList = new List<string>();
                                        if (!string.IsNullOrEmpty(LogSql))
                                        {
                                            sqlList.Add(LogSql);
                                        }
                                        //更新单据
                                        string updateSql = string.Format(@"/*dialect*/ update t_AR_receivable set F_DEV_FDATE='{0}',F_DEV_FSTATUS='{1}' 
                    where FID={2}", interfaceLog.FDATE, "删除失败", FID);
                                        sqlList.Add(updateSql);
                                        DBServiceHelper.ExecuteBatch(this.Context, sqlList);
                                        #endregion
                                        throw new KDBusinessException("", "单据同步删除CRM失败，禁止删除");
                                    }
                                

                            }
                            else if (resultSearch.Contains("操作者未找到"))
                            {
                                #region 退货单写日志(插入一张CRM接口日志单据，更新单据上的接口调用方式/调用时间/调用结果）
                                Common.InterfaceLog interfaceLog = new Common.InterfaceLog();
                                interfaceLog.FBILLNO = FBillNo;
                                interfaceLog.FBILLID = FID;
                                interfaceLog.FDATE = System.DateTime.Now;
                                interfaceLog.FINTERNAME = "删除出库单";
                                interfaceLog.FInvokeType = "";
                                interfaceLog.Ftoken = "";
                                interfaceLog.FSTATUS = "失败";
                                interfaceLog.FRequsetData = "{\"operationinfo\":{\"operator\":\""+SalerNo+"\"},\"mainTable\":{\"djbm\":\"" + FBillNo + "\"},\"header\":{\"systemid\":\"kingdee\",\"currentDateTime\":\"" + DateTime.Now + "\",\"Md5\":\"md5OfStr \"}}";
                                interfaceLog.FReturnData = resultSearch;
                                interfaceLog.FRequest = "{\"operationinfo\":{\"operator\":\""+SalerNo+"\"},\"mainTable\":{\"djbm\":\"" + FBillNo + "\"},\"header\":{\"systemid\":\"kingdee\",\"currentDateTime\":\"" + DateTime.Now + "\",\"Md5\":\"md5OfStr \"}}";
                                interfaceLog.FReturn = resultSearch;
                                string LogSql = interfaceLog.WriteCRMLogSql();//获取写入日志单据的SQL
                                List<string> sqlList = new List<string>();
                                if (!string.IsNullOrEmpty(LogSql))
                                {
                                    sqlList.Add(LogSql);
                                }
                                //更新单据
                                string updateSql = string.Format(@"/*dialect*/ update t_AR_receivable set F_DEV_FDATE='{0}',F_DEV_FSTATUS='{1}' 
                    where FID={2}", interfaceLog.FDATE, "删除失败", FID);
                                sqlList.Add(updateSql);
                                DBServiceHelper.ExecuteBatch(this.Context, sqlList);
                                #endregion
                                throw new KDBusinessException("", resultSearch);
                            }
                        }
                       
                    }
                }
            }
        }

        /// <summary>
        /// api配置
        /// </summary>
        public DataTable APISetting(string InterfaceName)
        {
            string Sql = string.Format(@"select * from RDLV_t_CRMInterface where F_RDLV_InterfaceName='{0}'", InterfaceName);
            return DBServiceHelper.ExecuteDataSet(this.Context, Sql).Tables[0];
        }


        /// <summary>
        /// CRM新增退货单接口
        /// </summary>
        public  Return CRMAddRETURNSTOCK(ProvisionalReceivablesReturnsModel.mainTableList mainTable, List<ProvisionalReceivablesReturnsModel.detailList> detail1,string UserAccount)
        {
            //当前日期
            String currentDate = DateTime.Now.ToString("yyyy-MM-dd");
            //当前时间
            String currentTime = DateTime.Now.ToString("hh:mm:ss");

            string requestUri1 = "http://10.10.17.127:8086/api/cube/restful/interface/saveOrUpdateModeData/create_returns_order";

            //系统标识
            String systemid = "kingdee";
            //密码
            String d_password = "p@ssw0rd...";
            DataTable dt= APISetting("新增退货单");  
            if (dt.Rows.Count>0)
            {
                requestUri1 = Convert.ToString(dt.Rows[0]["F_RDLV_URL"]);
                systemid = Convert.ToString(dt.Rows[0]["F_RDLV_SystemId"]);
                d_password = Convert.ToString(dt.Rows[0]["F_RDLV_Password"]);
            }
            //获取时间戳
            String currentTimeTamp = getTimestamp();
            String md5Source = systemid + d_password + currentTimeTamp;
            String md5OfStr = Md5(md5Source).ToLower();

            Return result = PostToPushNews(requestUri1, systemid, currentTimeTamp, md5OfStr, mainTable, detail1, UserAccount);


            return result;
        }

        /// <summary>
        /// CRM更新退货单接口
        /// </summary>
        public  Return CRMUpdateRETURNSTOCK(ProvisionalReceivablesReturnsModel.mainTableList mainTable, List<ProvisionalReceivablesReturnsModel.detailList> detail1,string UserAccount)
        {
            //当前日期
            String currentDate = DateTime.Now.ToString("yyyy-MM-dd");
            //当前时间
            String currentTime = DateTime.Now.ToString("hh:mm:ss");

            string requestUri1 = "http://10.10.17.127:8086/api/cube/restful/interface/saveOrUpdateModeData/update_returns_order";

            //系统标识
            String systemid = "kingdee";
            //密码
            String d_password = "p@ssw0rd...";
            DataTable dt = APISetting("更新退货单");
            if (dt.Rows.Count>0)
            {
                requestUri1 = Convert.ToString(dt.Rows[0]["F_RDLV_URL"]);
                systemid = Convert.ToString(dt.Rows[0]["F_RDLV_SystemId"]);
                d_password = Convert.ToString(dt.Rows[0]["F_RDLV_Password"]);
            }
            //获取时间戳
            String currentTimeTamp = getTimestamp();
            String md5Source = systemid + d_password + currentTimeTamp;
            String md5OfStr = Md5(md5Source).ToLower();

            Return result = PostToUpdateNews(requestUri1, systemid, currentTimeTamp, md5OfStr, mainTable, detail1, UserAccount);


            return result;
        }
      

     

        /// <summary>
        /// CRM查询退货单接口
        /// </summary>
        public  string CRMSearchRETURNSTOCK(string djnm,string UserAccount)
        {
            //当前日期
            String currentDate = DateTime.Now.ToString("yyyy-MM-dd");
            //当前时间
            String currentTime = DateTime.Now.ToString("hh:mm:ss");

            string requestUri1 = "http://10.10.17.127:8086/api/cube/restful/interface/getDataByPK/select_returns_order";

            //系统标识
            String systemid = "kingdee";
            //密码
            String d_password = "p@ssw0rd...";
            DataTable dt = APISetting("查询退货单");
            if (dt.Rows.Count>0)
            {
                requestUri1 = Convert.ToString(dt.Rows[0]["F_RDLV_URL"]);
                systemid = Convert.ToString(dt.Rows[0]["F_RDLV_SystemId"]);
                d_password = Convert.ToString(dt.Rows[0]["F_RDLV_Password"]);
            }
            //获取时间戳
            String currentTimeTamp = getTimestamp();
            String md5Source = systemid + d_password + currentTimeTamp;
            String md5OfStr = Md5(md5Source).ToLower();

            string result = PostToSearchNews(requestUri1, systemid, currentTimeTamp, md5OfStr, djnm, UserAccount);


            return result;
        }

        /// <summary>
        /// CRM删除退货单接口
        /// </summary>
        public  string CRMDeleteRETURNSTOCK(string djnm,string UserAccount)
        {
            //当前日期
            String currentDate = DateTime.Now.ToString("yyyy-MM-dd");
            //当前时间
            String currentTime = DateTime.Now.ToString("hh:mm:ss");

            string requestUri1 = "http://10.10.17.127:8086/api/cube/restful/interface/deleteModeDataByPK/delete_returns_order";

            //系统标识
            String systemid = "kingdee";
            //密码
            String d_password = "p@ssw0rd...";
            DataTable dt = APISetting("删除退货单");
            if (dt.Rows.Count>0)
            {
                requestUri1 = Convert.ToString(dt.Rows[0]["F_RDLV_URL"]);
                systemid = Convert.ToString(dt.Rows[0]["F_RDLV_SystemId"]);
                d_password = Convert.ToString(dt.Rows[0]["F_RDLV_Password"]);
            }
            //获取时间戳
            String currentTimeTamp = getTimestamp();
            String md5Source = systemid + d_password + currentTimeTamp;
            String md5OfStr = Md5(md5Source).ToLower();

            string result = PostToDeleteNews(requestUri1, systemid, currentTimeTamp, md5OfStr, djnm, UserAccount);


            return result;
        }

        /// <summary>
        /// md5加密
        /// </summary>
        /// <param name="s"></param>
        /// <returns></returns>
        public static String Md5(string s)
        {
            char[] hexDigits = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };
            MD5 md5 = new MD5CryptoServiceProvider();
            byte[] inputBytes = System.Text.Encoding.ASCII.GetBytes(s);
            byte[] result = md5.ComputeHash(inputBytes);
            int j = result.Length;
            char[] str = new char[j * 2];
            int k = 0;
            for (int i = 0; i < j; i++)
            {
                byte byte0 = result[i];
                str[k++] = hexDigits[byte0 >> 4 & 0xf];
                str[k++] = hexDigits[byte0 & 0xf];
            }
            return new String(str);
        }

        /// <summary>
        /// CRM查询退货单POST
        /// </summary>
        public static string PostToSearchNews(string url, string systemid, string currentTimeTamp, string md5OfStr, string djnm,string UserAccount)
        {
            Dictionary<string, string> dic = new Dictionary<string, string>
            {
                {"datajson","{\"operationinfo\":{\"operator\":\"CRM\"},\"mainTable\":{\"djnm\":\""+djnm+"\"},\"header\":{\"systemid\":\""+systemid+"\",\"currentDateTime\":\""+currentTimeTamp+"\",\"Md5\":\""+md5OfStr+"\"}}"}
            };
            string result = string.Empty;
            HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
            req.Method = "POST";
            req.ContentType = "application/x-www-form-urlencoded;charset=utf-8";
            #region 添加Post 参数
            StringBuilder builder = new StringBuilder();
            int i = 0;
            foreach (var item in dic)
            {
                if (i > 0)
                    builder.Append("&");
                builder.AppendFormat("{0}={1}", item.Key, item.Value);
                i++;
            }
            byte[] data = Encoding.UTF8.GetBytes(builder.ToString());
            req.ContentLength = data.Length;
            using (Stream reqStream = req.GetRequestStream())
            {
                reqStream.Write(data, 0, data.Length);
                reqStream.Close();
            }
            #endregion

            HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
            Stream stream = resp.GetResponseStream();
            //获取响应内容
            using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
            {
                result = reader.ReadToEnd();
            }
            //string[] resAry = result.Split(new string[] { "result" }, StringSplitOptions.None);
            //string json = resAry[resAry.Length - 1].Remove(0, 3);
            //json= Regex.Replace(json, "\"\"", "\"");
            //json = json.Remove(json.Length - 2, 2);
            //json = Regex.Unescape(json);
            //if (json == "{}")
            //{
            //    return "无结果";
            //}
            //else
            //{
            //    Dictionary<string, object> dicJson = JsonConvert.DeserializeObject<Dictionary<string, object>>(json);
            //    Dictionary<string, object> mainTableJson = JsonConvert.DeserializeObject<Dictionary<string, object>>(dicJson["mainTable"].ToString());
            //    string returnCode = mainTableJson["djnm"].ToString();
            //    return returnCode;
            //}
            JObject jo = (JObject)JsonConvert.DeserializeObject(result);
            if (jo == null)
            {
                return "无结果";
            }
            else if (jo.ToString().Contains("status"))
            {
                string returnCode = jo["info"].ToString();
                return returnCode;
            }
            else if (jo["result"].ToString() == "{}")
            {
                return "无结果";
            }
            else
            {

                JToken rtToken = jo.SelectToken("result");
                JObject rt = (JObject)JsonConvert.DeserializeObject(rtToken.ToString());
                JToken mtToken = rt.SelectToken("mainTable");
                JObject mt = (JObject)JsonConvert.DeserializeObject(mtToken.ToString());
                string returnCode = mt["djnm"].ToString();
                return returnCode;
            }
        }

       

        /// <summary>
        /// CRM新增退货单POST
        /// </summary>
        public static Return PostToPushNews(string url, string systemid, string currentTimeTamp, string md5OfStr, ProvisionalReceivablesReturnsModel.mainTableList mainTable, List<ProvisionalReceivablesReturnsModel.detailList> detail1,string UserAccount)
        {
            Dictionary<string, string> dic = new Dictionary<string, string>
            {
                {"datajson","{\"data\":[{\"operationinfo\":{\"operator\":\"CRM\",\"operationDate\":\""+DateTime.Now.ToString("yyyy-MM-dd")+"\",\"operationTime\":\""+DateTime.Now.ToString("HH:mm:ss")+"\"},\"mainTable\":"+JsonConvert.SerializeObject(mainTable)+",\"detail1\":"+JsonConvert.SerializeObject(detail1)+"}],\"header\":{\"systemid\":\""+systemid+"\",\"currentDateTime\":\""+currentTimeTamp+"\",\"Md5\":\""+md5OfStr+"\"}}"}
            };
            string result = string.Empty;
            HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
            req.Method = "POST";
            req.ContentType = "application/x-www-form-urlencoded;charset=utf-8";
            #region 添加Post 参数
            StringBuilder builder = new StringBuilder();
            int i = 0;
            foreach (var item in dic)
            {
                if (i > 0)
                    builder.Append("&");
                builder.AppendFormat("{0}={1}", item.Key, item.Value);
                i++;
            }
            byte[] data = Encoding.UTF8.GetBytes(builder.ToString());
            req.ContentLength = data.Length;
            using (Stream reqStream = req.GetRequestStream())
            {
                reqStream.Write(data, 0, data.Length);
                reqStream.Close();
            }
            #endregion

            HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
            Stream stream = resp.GetResponseStream();
            //获取响应内容
            using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
            {
                result = reader.ReadToEnd();
            }
            Return @return = new Return();
            //string[] sArray = result.Split(new string[] { "}}\",\"status\":\"", "}]" }, StringSplitOptions.None);
            string[] resAry = result.Split(new string[] { "status" }, StringSplitOptions.None);
            string[] json = result.Split(new string[] { "datajson" }, StringSplitOptions.None);
            //if (resAry[resAry.Length - 1].IndexOf("1") > -1)
            //{
            string status = "";
            status = resAry[resAry.Length - 1].Replace("\"", "");
            status = status.Replace(":", "");
            status = status.Replace("}", "");
            string json1 = json[json.Length - 1].Remove(0, 3);
            json1 = Regex.Replace(json1, "\"\"", "\"");
            json1 = json1.Remove(json1.Length - 2, 2);
            json1 = Regex.Unescape(json1);
            json1 = Regex.Unescape(json1);
            //}
            @return.status = status;
            @return.datajson = json1;
            return @return;
        }
     
  

        /// <summary>
        /// CRM更新退货单POST
        /// </summary>
        public static Return PostToUpdateNews(string url, string systemid, string currentTimeTamp, string md5OfStr, ProvisionalReceivablesReturnsModel.mainTableList mainTable, List<ProvisionalReceivablesReturnsModel.detailList> detail1,string UserAccount)
        {

            Dictionary<string, string> dic = new Dictionary<string, string>
            {
                {"datajson","{\"data\":[{\"operationinfo\":{\"operator\":\"CRM\",\"operationDate\":\""+DateTime.Now.ToString("yyyy-MM-dd")+"\",\"operationTime\":\""+DateTime.Now.ToString("HH:mm:ss")+"\"},\"mainTable\":"+JsonConvert.SerializeObject(mainTable)+",\"detail1\":"+JsonConvert.SerializeObject(detail1)+"}],\"header\":{\"systemid\":\""+systemid+"\",\"currentDateTime\":\""+currentTimeTamp+"\",\"Md5\":\""+md5OfStr+"\"}}"}
            };
            string result = string.Empty;
            HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
            req.Method = "POST";
            req.ContentType = "application/x-www-form-urlencoded;charset=utf-8";
            #region 添加Post 参数
            StringBuilder builder = new StringBuilder();
            int i = 0;
            foreach (var item in dic)
            {
                if (i > 0)
                    builder.Append("&");
                builder.AppendFormat("{0}={1}", item.Key, item.Value);
                i++;
            }
            string b = builder.ToString();
            byte[] data = Encoding.UTF8.GetBytes(builder.ToString());
            req.ContentLength = data.Length;
            using (Stream reqStream = req.GetRequestStream())
            {
                reqStream.Write(data, 0, data.Length);
                reqStream.Close();
            }
            #endregion

            HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
            Stream stream = resp.GetResponseStream();
            //获取响应内容
            using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
            {
                result = reader.ReadToEnd();
            }
            Return @return = new Return();
            result = Regex.Unescape(result);//去除转义符
            result = Regex.Unescape(result);//去除转义符
            string[] resAry = result.Split(new string[] { "status" }, StringSplitOptions.None);
            string[] json = result.Split(new string[] { "datajson" }, StringSplitOptions.None);
            string status = "";
            status = resAry[resAry.Length - 1].Replace("\"", "");
            status = status.Replace(":", "");
            status = status.Replace("}", "");
            string json1 = json[json.Length - 1].Remove(0, 3);
            json1 = Regex.Replace(json1, "\"\"", "\"");
            json1 = Regex.Unescape(json1);
            json1 = Regex.Unescape(json1);
            //}
            @return.status = status;
            @return.datajson = json1;
            return @return;
        }


        /// <summary>
        /// CRM删除退货单POST
        /// </summary>
        public static string PostToDeleteNews(string url, string systemid, string currentTimeTamp, string md5OfStr, string djnm,string UserAccount)
        {
            Dictionary<string, string> dic = new Dictionary<string, string>
            {
                {"datajson","{\"operationinfo\":{\"operator\":\"CRM\"},\"mainTable\":{\"djnm\":\""+djnm+"\"},\"header\":{\"systemid\":\""+systemid+"\",\"currentDateTime\":\""+currentTimeTamp+"\",\"Md5\":\""+md5OfStr+"\"}}"}
            };
            string result = string.Empty;
            HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
            req.Method = "POST";
            req.ContentType = "application/x-www-form-urlencoded;charset=utf-8";
            #region 添加Post 参数
            StringBuilder builder = new StringBuilder();
            int i = 0;
            foreach (var item in dic)
            {
                if (i > 0)
                    builder.Append("&");
                builder.AppendFormat("{0}={1}", item.Key, item.Value);
                i++;
            }
            byte[] data = Encoding.UTF8.GetBytes(builder.ToString());
            req.ContentLength = data.Length;
            using (Stream reqStream = req.GetRequestStream())
            {
                reqStream.Write(data, 0, data.Length);
                reqStream.Close();
            }
            #endregion

            HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
            Stream stream = resp.GetResponseStream();
            //获取响应内容
            using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
            {
                result = reader.ReadToEnd();
            }
            string[] resAry = result.Split(new string[] { "result" }, StringSplitOptions.None);
            string json = resAry[resAry.Length - 1].Remove(0, 3);
            //json = json.Remove(json.Length - 2, 2);
            json = Regex.Unescape(json);
            json = Regex.Replace(json, "\"\"", "\"");
            string[] message= json.Split(new string[] { "message" }, StringSplitOptions.None);

            if (json == "{}")
            {
                return "无结果";
            }
            else
            {

                return message[1].Substring(3,4);
            }
        }


        /**
       * 获取时间戳   格式如：19990101235959
       * @return
       */
        public static String getTimestamp()
        {

            return DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss").Replace("-", "").Replace(":", "").Replace(" ", "").Replace("/", "");
        }


        /**
       * 接口返回值自定义 
       */
        public class Return
        {
            public string status { get; set; }
            public string datajson { get; set; }
        }
    }
}

